package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author mengwei
 * @date 2019/8/21
 * @desc
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    MemberService memberService;

    @Reference
    SetmealService setmealService;

    @Reference
    ReportService reportService;

    /**
     * 获取会员每月增长数据 折线图
     * {
     *     months: []
     *      memberCount:[]
     * }
     *
     *
     * @return
     */
    @RequestMapping("/findMemberByDate")
    public Result findMemberByDate(String valueDate){

        // 返回的日期集合
        List<String> days = new ArrayList<String>();
        //创建map集合 接收数据
        Map<String,Object> map = new HashMap<>();

        List<Long> countList;

        try {
            //截取日期 以逗号为分隔符
            String[] splitDate = valueDate.split(",");
            //将日期转为yyyy-MM
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
            System.out.println("日期时间是:"+valueDate);

            //开始时间 获取 索引中的第一个元素   2019-1-1,2019-1-2
            Date begin =dateFormat.parse(splitDate[0]);
            //结束时间 获取索引中的第二个元素  2019-1-1,2019-1-2
            Date end  = dateFormat.parse(splitDate[1]);

            //创建日历 添加开始时间
            Calendar calendarBegin =  Calendar.getInstance();
            calendarBegin.setTime(begin);
            //创建日历 添加结束时间
            Calendar calendarEnd =  Calendar.getInstance();
            calendarEnd.setTime(end);
            //月份加1(包含结束)
            calendarEnd.add(Calendar.MONTH,+1);
            while (calendarBegin.before(calendarEnd)){
                days.add(dateFormat.format(calendarBegin.getTime()));
                calendarBegin.add(Calendar.MONTH,1);
            }
            countList = memberService.findMemberByDate(days);



            map.put("memberCount",countList);
            map.put("months",days);

            return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);


        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL );
        }
    }

    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        try {
            Map<String, Object> map = memberService.getMemberReport();
            return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        try {
            Map<String, Object> map = setmealService.getSetmealReport();
            return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConst.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /*
    * 会员统计
    * 按照性别进行统计
    * */
    @RequestMapping("/getMemberSex")
    public Result getMemberSex(){
        try {
            Map<String,Object> map=memberService.getMemberSex();
            return new Result(true,MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }
    /*
    * 会员统计
    * 按照年龄段进行统计
    * */
    @RequestMapping("/getMemberAge")
    public Result getMemberAge(){
        try {
            Map<String,Object> map = memberService.getMemberAge();
//            System.out.println(map);
            return new Result(true,MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response) {
        try {
            //获取运营统计数据
            Map<String, Object> map = reportService.getBusinessReportData();
            //构建模板流对象
            InputStream in = this.getClass().getResourceAsStream("/template/report_template.xlsx");
            //获取excel对象
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            //获取工作表对象
            XSSFSheet sheet = workbook.getSheetAt(0);

            //reportDate:   统计日期（今天）
            XSSFRow row = sheet.getRow(2);
            XSSFCell cell = row.getCell(5);
            cell.setCellValue(String.valueOf(map.get("reportDate")));

            //todayNewMember :0,  今日新增会员数
            row = sheet.getRow(4);
            cell = row.getCell(5);
            cell.setCellValue(String.valueOf(map.get("todayNewMember")));

            //totalMember :0,     会员总数
            row = sheet.getRow(4);
            cell = row.getCell(7);
            cell.setCellValue(String.valueOf(map.get("totalMember")));

            //thisWeekNewMember :0,   本周新增会员数（周一以后新增了多少会员）
            row = sheet.getRow(5);
            cell = row.getCell(5);
            cell.setCellValue(String.valueOf(map.get("thisWeekNewMember")));

            //thisMonthNewMember :0,  本月新增会员数（1号以后新增了多少会员）
            row = sheet.getRow(5);
            cell = row.getCell(7);
            cell.setCellValue(String.valueOf(map.get("thisMonthNewMember")));

            //todayOrderNumber :0,    今日预约数（预约今天来体检的人数）
            row = sheet.getRow(7);
            cell = row.getCell(5);
            cell.setCellValue(String.valueOf(map.get("todayOrderNumber")));

            //todayVisitsNumber :0,   今日到诊数（今天实际有多少人体检）
            row = sheet.getRow(7);
            cell = row.getCell(7);
            cell.setCellValue(String.valueOf(map.get("todayVisitsNumber")));

            //thisWeekOrderNumber :0, 本周预约数（预约本周（周一~~~周日）来体检的人数）
            row = sheet.getRow(8);
            cell = row.getCell(5);
            cell.setCellValue(String.valueOf(map.get("thisWeekOrderNumber")));

            //thisWeekVisitsNumber :0, 本周到诊数（本周（周一以后）实际来了多少人）
            row = sheet.getRow(8);
            cell = row.getCell(7);
            cell.setCellValue(String.valueOf(map.get("thisWeekVisitsNumber")));

            //thisMonthOrderNumber :0,  本月预约数（预约本月（1号--月底）来体检的人数）
            row = sheet.getRow(9);
            cell = row.getCell(5);
            cell.setCellValue(String.valueOf(map.get("thisMonthOrderNumber")));

            //thisMonthVisitsNumber :0, 本月到诊数(本月1号以后实际来了多少人)
            row = sheet.getRow(9);
            cell = row.getCell(7);
            cell.setCellValue(String.valueOf(map.get("thisMonthVisitsNumber")));

            //hotSetmeal （热门套餐）:[
            //{name:'阳光爸妈升级肿瘤12项筛查（男女单人）体检套餐',setmeal_count:200,proportion:0.222},
            //{name:'阳光爸妈升级肿瘤12项筛查体检套餐',setmeal_count:200,proportion:0.222}
            //]
            List<Map<String, Object>> hotSetmeals = (List<Map<String, Object>>) map.get("hotSetmeal");
            int rowNumber = 12;
            for (Map<String, Object> hotSetmeal : hotSetmeals) {
                row = sheet.getRow(rowNumber);
                cell = row.getCell(4);
                cell.setCellValue(String.valueOf(hotSetmeal.get("name")));

                row = sheet.getRow(rowNumber);
                cell = row.getCell(5);
                cell.setCellValue(String.valueOf(hotSetmeal.get("setmeal_count")));

                row = sheet.getRow(rowNumber);
                cell = row.getCell(6);
                cell.setCellValue(String.valueOf(hotSetmeal.get("proportion")));

                rowNumber++;
            }

            // 通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            //设置输入的文件的类型
            response.setContentType("application/vnd.ms-excel");
            String todayDate = DateUtils.parseDate2String(new Date());
            response.setHeader("content-Disposition", "attachment;filename=" + todayDate + "report.xlsx");
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
